package cool.xiaokang.familyaccount.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cool.xiaokang.familyaccount.pojo.User;
import cool.xiaokang.familyaccount.service.UserService;
import cool.xiaokang.familyaccount.utils.CryptographyUtil;
import cool.xiaokang.familyaccount.utils.MainMail;
import cool.xiaokang.familyaccount.utils.PageBean;
import cool.xiaokang.familyaccount.utils.ResponseUtils;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Scope("prototype")
@Controller
public class UserAction extends ActionSupport implements ModelDriven<User> {
	private static final long serialVersionUID = -295036285433836301L;
	private JSONObject jsonObject = new JSONObject();
	private User user = new User();
	@Autowired
	private UserService userService;

	private String checkcode;
	private String keyword;
	private String oldpwd;
	private Integer page;
	private Integer rows;
	private String user_ids;

	// 用户登录
	public String login() throws Exception {
		Map<String, Object> map = ActionContext.getContext().getSession();
		// 取出session中的验证码
		String validatecode = (String) map.get("key");
		if (StringUtils.isNotBlank(checkcode) && checkcode.equalsIgnoreCase(validatecode)
				&& StringUtils.isNotBlank(user.getUser_name().trim())) {
			Subject subject = SecurityUtils.getSubject();
			String cryptographyPwd = CryptographyUtil.md5(user.getUser_password().trim(),
					CryptographyUtil.md5(CryptographyUtil.FAMILY, user.getUser_name().trim()));
			AuthenticationToken token = new UsernamePasswordToken(user.getUser_name().trim(), cryptographyPwd);
			try {
				subject.login(token);
				User currentUser = (User) subject.getPrincipal();
				// 判断用户是否被封禁
				if (currentUser.getState() == '1') {
					return "contactXiaokang";
				} else {
					ActionContext.getContext().getSession().put("currentUser", currentUser);
					return "welcome";
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.addActionError("用户名或密码输入错误！");
				return "toLogin";
			}
		} else {
			this.addActionError("输入的验证码有误！");
			return "toLogin";
		}
	}

	// 用户注册
	public String regist() throws Exception {
		Map<String, Object> map = ActionContext.getContext().getSession();
		String validatecode = (String) map.get("key");
		if (StringUtils.isNotBlank(checkcode) && checkcode.equalsIgnoreCase(validatecode)) {
			if (StringUtils.isBlank(user.getUser_name()) || StringUtils.isBlank(user.getUser_password())) {
				return "toRegist";
			}
			try {
				userService.saveUser(user);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "toSuccess";
		} else {
			return "toRegist";
		}
	}

	// 注销退出
	public String logout() throws Exception {
		User user = (User) ActionContext.getContext().getSession().get("currentUser");
		user.setLoginDate(new Date());
		userService.update(user);
		ActionContext.getContext().getSession().remove("currentUser");
		return LOGIN;
	}

	// 编辑个人信息
	public String edit() {
		User currentUser = (User) ActionContext.getContext().getSession().get("currentUser");
		user.setUser_id(currentUser.getUser_id());
		user.setUser_password(currentUser.getUser_password());
		user.setRegister_date(currentUser.getRegister_date());
		user.setState(currentUser.getState());
		user.setLevel(currentUser.getLevel());
		user.setLoginDate(currentUser.getLoginDate());
		user.setRealname(currentUser.getRealname());
		user.setIdcard(currentUser.getIdcard());
		user.setAddress(currentUser.getAddress());
		if (StringUtils.isBlank(user.getFace())) {
			user.setFace(null);
		}
		if ("".equals(user.getUser_sex())) {
			user.setUser_sex(null);
		}
		userService.update(user);
		ActionContext.getContext().getSession().put("currentUser", user);
		return "userDesc";
	}

	// 找回密码时校验密码是否是原密码
	public String checkOldPassword() throws Exception {
		User u = (User) ActionContext.getContext().getSession().get("currentUser");
		String user_password = u.getUser_password();
		String old = CryptographyUtil.md5(oldpwd, CryptographyUtil.md5(CryptographyUtil.FAMILY, u.getUser_name()));
		boolean flag = false;
		if (old.equals(user_password)) {
			flag = true;
		}
		jsonObject.put("isExist", flag);
		ResponseUtils.respJsonWithJSONObject(ServletActionContext.getResponse(), jsonObject);
		return NONE;
	}

	// 在线修改密码
	public String editPwd() throws Exception {
		User u = (User) ActionContext.getContext().getSession().get("currentUser");
		if (StringUtils.isNotBlank(user.getUser_password())) {
			String newPwd = CryptographyUtil.md5(user.getUser_password().trim(),
					CryptographyUtil.md5(CryptographyUtil.FAMILY, u.getUser_name().trim()));
			u.setUser_password(newPwd);
			userService.update(u);
			ServletActionContext.getContext().getSession().remove("currentUser");
			return LOGIN;
		} else {
			return "toRegist";
		}
	}

	// 注册时检查用户名是否重复
	public String checkName() throws IOException {
		boolean flag = userService.findUserByName(user.getUser_name().trim());
		jsonObject.put("isExist", flag);
		ResponseUtils.respJsonWithJSONObject(ServletActionContext.getResponse(), jsonObject);
		return NONE;
	}

	// 注册时检查邮箱是否重复
	public String checkEmail() throws IOException {
		boolean flag = userService.findUserByEmail(user.getEmail().trim());
		jsonObject.put("isExist", flag);
		ResponseUtils.respJsonWithJSONObject(ServletActionContext.getResponse(), jsonObject);
		return NONE;
	}

	// 检验找回密码的输入
	public String findPwd() {
		Map<String, Object> map = ActionContext.getContext().getSession();
		String validatecode = (String) map.get("key");
		if (StringUtils.isNotBlank(checkcode) && checkcode.equalsIgnoreCase(validatecode)) {
			if (StringUtils.isNotBlank(keyword)) {
				User u = userService.findUserByKeyWord(keyword);
				if (u != null) {
					ActionContext.getContext().put("user_id", u.getUser_id());
					Random rand = new Random();
					String hash1 = Integer.toHexString(rand.nextInt());
					String capstr = hash1.substring(0, 6);
					try {
						MainMail.sendMyEMail(u.getEmail(), u.getUser_name(), capstr);
					} catch (Exception e) {
						e.printStackTrace();
						this.addActionError("发送邮箱出错了");
						return "findPwd";
					}
					ActionContext.getContext().getSession().put("key", capstr);
					return "updatePwd";
				} else {
					this.addActionError("用户名或者邮箱不存在！");
					return "findPwd";
				}
			} else {
				this.addActionError("用户名或者邮箱不能为空！");
				return "findPwd";
			}
		} else {
			this.addActionError("验证码输入错误！");
			return "findPwd";
		}
	}

	// 校验验证码是否正确
	public String checkCode() throws IOException {
		String key = (String) ActionContext.getContext().getSession().get("key");
		if (checkcode.equalsIgnoreCase(key)) {
			jsonObject.put("isExist", true);
		} else {
			jsonObject.put("isExist", false);
		}
		ResponseUtils.respJsonWithJSONObject(ServletActionContext.getResponse(), jsonObject);
		return NONE;
	}

	// 更新密码
	public String updatePwd() {
		String key = (String) ActionContext.getContext().getSession().get("key");
		if (StringUtils.isNotBlank(checkcode) && checkcode.equals(key) && user.getUser_id() != null) {
			userService.updatePwd(user);
			// 置空发送的验证码
			ActionContext.getContext().getSession().put("key", "");
			return "login";
		}
		return "toFind";
	}

	// 后台分页查询所有用户
	@SuppressWarnings("unchecked")
	@RequiresPermissions("user-list")
	public String pageQuery() throws IOException {
		PageBean pb = new PageBean();
		DetachedCriteria dc = DetachedCriteria.forClass(User.class);
		if (StringUtils.isNotBlank(user.getUser_name())) {
			dc.add(Restrictions.like("user_name", "%" + user.getUser_name() + "%"));
		}
		if (StringUtils.isNotBlank(user.getIdcard())) {
			dc.add(Restrictions.eq("idcard", user.getIdcard().trim()));
		}
		if (StringUtils.isNotBlank(user.getUser_phone())) {
			dc.add(Restrictions.eq("user_phone", user.getUser_phone().trim()));
		}
		if (user.getState() != null) {
			dc.add(Restrictions.eq("state", user.getState()));
		}
		if (user.getLevel() != null) {
			dc.add(Restrictions.eq("level", user.getLevel()));
		}
		pb.setDetachedCriteria(dc);
		pb.setCurrentPage(page);
		pb.setPageSize(rows);
		userService.pageQuery(pb);
		List<User> users = pb.getRows();
		StringBuffer sBuffer = new StringBuffer("[");
		int i = 0;
		for (User user : users) {
			String fieldToJson = ResponseUtils.fieldToJson(user);
			int lastIndex = users.size() - 1;
			if (i == lastIndex) {
				sBuffer.append(fieldToJson);
			} else {
				sBuffer.append(fieldToJson + ",");
			}
			i++;
		}
		sBuffer.append("]");
//		System.out.println(sBuffer.toString());
		StringBuffer respStr = new StringBuffer("{\"rows\":");
		respStr.append(sBuffer.toString());
		respStr.append(",\"total\":");
		respStr.append(pb.getTotal());
		respStr.append("}");
		ResponseUtils.respJsonString(ServletActionContext.getResponse(), respStr.toString());
		return NONE;
	}

	// 封禁用户
	@RequiresPermissions("user-stop")
	public String stop() {
		userService.stop(user_ids);
		return "userList";
	}

	// 解封用户
	@RequiresPermissions("user-open")
	public String open() {
		userService.open(user_ids);
		return "userList";
	}

	// 修改用户等级
	@RequiresPermissions("user-level")
	public String editLevel() {
		userService.editLevel(user);
		return "userList";
	}

	@Override
	public User getModel() {
		return user;
	}

}
